<template>
  <div class="sms-tempalte-wrapper" v-loading="loading">
    <div class="left-template">
      <div class="sms-type">
        <div class="head-title">
          <div>模板类别</div>
          <div @click="handleAdd">
            <el-icon><plus /></el-icon>
          </div>
        </div>
        <div class="sms-type-content">
          <div class="sms-type-item" v-for="item in smsCategoryList">
            <div>{{item.typeName}}</div>
            <div>
              <span @click="hanledEdit(item)"><el-icon><edit /></el-icon></span>
              <span @click="handleDel(item)"><el-icon><delete /></el-icon></span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="right-template">
      <div class="right-template-head">
        <div class="add-btn" @click="addSmsModel">新建模板</div>
      </div>
      <div class="right-template-table">
          <ztable 
            :tableData='smsTabelData' 
            :strucs='columns'
            :height="'100%'"
            :isshowOperation="true"
          >
            <template #default="slotScope">
              <el-button type="text" class="operation" @click="handleSmsItemEdit(slotScope.rowData)">修改</el-button>
              <el-button type="text" class="operation" @click="handleSmsItemDel(slotScope.rowData)">删除</el-button>
            </template>
          </ztable>
      </div>
      
    </div>
  </div>

  <!-- 类别 -->
  <zdialog 
    :title="dilogtitle" 
    :width="'30%'" 
    @handleClose="closeOperation" 
    v-model="openOperation" 
    :btnData="dialogBtnData">
      <template #body>
        <div class="leftToRight-layout">
          <div class="label">
            <span>短信类别</span>
          </div>
          <div class="operations">
            <el-input
                v-model="smsCategory"
                >
              </el-input>
          </div>
        </div>
      </template>
    </zdialog>

    <!-- 短信模板 -->
  <zdialog 
    :title="drawerTitle" 
    :width="'40%'" 
    @handleClose="drawerClose" 
    v-model="drawer" 
    :btnData="dialogModelBtn">
    <template #body>
      <div class="sms-phone">
        <div class="content">
          <div class="sms-content">
            <div class="leftToRight-layout" >
                <div class="label">
                  <span>模板类别</span>
                </div>
                <div class="operations">
                  <el-select v-model="typeId"  placeholder="请选择">
                    <el-option
                      v-for="item in smsCategoryList"
                      :key="item.id"
                      :label="item.typeName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </div>
              </div>
              <div class="leftToRight-layout" >
                <div class="label">
                  <span>短信名称</span>
                </div>
                <div class="operations">
                  <el-input
                      v-model="title"
                      >
                    </el-input>
                </div>
              </div>
              <div class="leftToRight-layout" >
                <div class="label">
                  <span>短信内容</span>
                </div>
                <div class="operations">
                  <el-input
                      type="textarea"
                      v-model="content"
                      :rows="6"
                      >
                    </el-input>
                    <span class="tips">共<span 
                      class="font-color-red"
                      :class="{'font-size-green': count}"
                      >{{count}}</span> 个字，按<span class="font-size-green">{{totalCount}}</span>条 短信计算</span>
                      <div class="font-color-red">注意: {{'短信字数<=70个字，按照70个字一条短信计算。中文英文符号统一计算为一个字符'}}</div>
                </div>
              </div>

          </div>
          <div class="phone-content">
            <img class="phone-img" :src="phonerImg" alt="phone">
            <div class="view-content">
              <div>【辉煌口腔】{{content}}
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
    </zdialog>

    
</template>

<script lang="ts">
import { Plus, Delete, Edit } from '@element-plus/icons-vue'
import { defineComponent, reactive, toRefs, onMounted, watch } from 'vue';
import zdialog from '@components/dialog/dialog.vue'
import ztable from '@components/Table/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import useRequest from '../../../hook/request'
import phonerImg from '../../../assets/image/phone.png'


type SmsCategoryList = {
  typeName: string,
  id: number
}

type SmsTableData = {
  content: string,
  createTime: string,
  id: number | string | any,
  typeId: any,
  title: string,
  typeName: string
}
export default defineComponent({
  name: 'SmsTemplate',
  components: {
    zdialog,
    ztable,

    Plus, Delete, Edit
  },
  setup() {
    const state = reactive({
      loading: false,
      dilogtitle: '',
      openOperation: false,
      smsCategory: '',
      smsTypeId: 0,
      smsCategoryList: <SmsCategoryList[]>[],

      smsTabelData: <SmsTableData[]>[],
      columns: [
        {
           id: 529,
            name: "typeName",
            viewName: "类别",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null
        },
        {
           id: 529,
            name: "title",
            viewName: "名称",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null
        },
        {
           id: 529,
            name: "content",
            viewName: "内容",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null
        },
        {
           id: 529,
            name: "createTime",
            viewName: "创建时间",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null
        },
      ],

      drawerTitle: '',
      drawer: false,
      content: '',
      title: '',
      typeId: '',
      count: 0,
      totalCount: 0,
      modelId: ''
    })
    onMounted(() => {
      getTypeList()
      getModelList()
    })
    watch(() => state.content,(newV)=> {
      console.log(newV.length)
      if(newV.length <= 70 && newV.length > 0) {
        state.totalCount = 1
      } else {
        state.totalCount = Math.ceil((newV.length / 70))
      }
      state.count = newV.length
    })
    const getTypeList = async() => {
      state.loading = true
      let result:any = await useRequest(`company/sms/model/getTypeList`, {}, 'POST')
      state.smsCategoryList = result.data
      state.loading = false
    }
    const handleAdd = () => {
      state.dilogtitle = '添加类别'
      state.openOperation = true
    }
    const hanledEdit = (data: SmsCategoryList) => {
      state.dilogtitle = '修改类别'
      state.openOperation = true
      state.smsCategory = data.typeName
      state.smsTypeId = data.id
    }

    const handleDel = (data: SmsCategoryList) => {
      ElMessageBox.confirm('此操作将删除该类别, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async() => {
        deleteSmsCategory(data)
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
      console.log('删除')
    }

    const closeOperation = () => {
      state.openOperation = false
      state.smsTypeId = 0
      state.smsCategory = ''
    }

    // 确定添加类别
    const addSmsCategory = async() => {
      let params = {
        typeName: state.smsCategory
      }
      try{
        let result:any = await useRequest(`company/sms/model/addType`, params, 'POST')
        closeOperation()
        ElMessage.success('添加类型' + result.msg)
        getTypeList()
      console.log(result)
      }catch(e) {
        console.log(e)
      }
      
    }

    // 确定修改类别
    const editSmsCategory = async() => {
      let params = {
        typeName: state.smsCategory
      } as SmsCategoryList
      if(state.smsTypeId) {
        params.id = state.smsTypeId
      }
      try{
        let result:any = await useRequest(`company/sms/model/updateType`, params, 'POST')
        closeOperation()
        ElMessage.success('修改类型' + result.msg)
        getTypeList()
      console.log(result)
      }catch(e) {
        console.log(e)
      }
    }

    // 删除类型
    const deleteSmsCategory = async(data: SmsCategoryList) => {
      try{
        let result:any = await useRequest(`company/sms/model/delType/${data.id}`, {}, 'POST')
        closeOperation()
        ElMessage.success('删除类型' + result.msg)
        getTypeList()
      console.log(result)
      }catch(e) {
        console.log(e)
      }
    }

    const dialogBtnData = [
      {
        name: '确定',
        func: () => {
          console.log('确定')
          if(state.dilogtitle === '添加类别') {
            addSmsCategory()
          }

          if(state.dilogtitle === '修改类别') {
            editSmsCategory()
          }
          
        }
      },
      {
        name: '取消',
        func: () => {
          console.log('取消')
          closeOperation()
        }
      }
    ]


    const drawerClose = () => {
      state.drawer = false
      state.content = ''
      state.typeId = '',
      state.modelId = ''
      state.title = ''

    }
    // 表格短信 获取
    const getModelList = async() => {
      state.loading = true
      let result:any = await useRequest(`company/sms/model/getModelList`, {}, 'POST')
      console.log(result)
      state.smsTabelData = result.data || []
      state.loading = false
    }

    const addSmsModel = () => {
      state.drawer = true
      state.drawerTitle = '新建短信模板'
    }

    const addModel = async() => {
      let params = {
        content: state.content,
        typeId: state.typeId,
        title: state.title
      }
      try{
        let result:any = await useRequest(`company/sms/model/addModel`, params, 'POST')
        drawerClose()
        ElMessage.success('新建短信模板' + result.msg)
        getModelList()

      }catch(e) {
        console.log(e)
      }

    }

    const updateModel = async() => {
      let params = {
        content: state.content,
        typeId: state.typeId,
        title: state.title,
        id: state.modelId
      }
      try{
        let result:any = await useRequest(`company/sms/model/updateModel`, params, 'POST')
        drawerClose()
        ElMessage.success('修改短信模板' + result.msg)
        getModelList()

      }catch(e) {
        console.log(e)
      }

    }

    const deleteSmsModel = async(data: SmsTableData) => {
      try{
        let result:any = await useRequest(`company/sms/model/delModel/${data.id}`, {}, 'POST')
        drawerClose()
        ElMessage.success('删除短信模板' + result.msg)
        getModelList()
      console.log(result)
      }catch(e) {
        console.log(e)
      }
    }

    // 表格短信 修改
    const handleSmsItemEdit = (rowData: SmsTableData) => {
      console.log(rowData)
      state.drawer = true
      state.drawerTitle = '修改短信模板'
      state.title = rowData.title
      state.typeId = rowData.typeId
      state.modelId = rowData.id
      state.content = rowData.content

    }
    // 表格短信 删除
    const handleSmsItemDel = (rowData: SmsTableData) => {
      ElMessageBox.confirm('此操作将删除该类别, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async() => {
        deleteSmsModel(rowData)
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
      console.log('表格删除', rowData)
    }

    const dialogModelBtn = [
      {
        name: '确定',
        func: () => {
          console.log('确定')
          if(state.drawerTitle === '新建短信模板') {
            addModel()
          }

          if(state.drawerTitle === '修改短信模板') {
            updateModel()
          }
          
        }
      },
      {
        name: '取消',
        func: () => {
          console.log('取消')
          drawerClose()
        }
      }
    ]

    
    return {
      handleAdd,
      hanledEdit,
      handleDel,
      closeOperation,
      handleSmsItemDel,
      handleSmsItemEdit,
      dialogBtnData,
      ...toRefs(state),
      addSmsModel,
      drawerClose,
      phonerImg,
      dialogModelBtn
    }
  }
})

</script>

<style lang="scss" scoped>

.sms-tempalte-wrapper {
  width: 100%;
  height: 100%;
  background-color: #fff;
  display: flex;

  .left-template {
    flex: 1;
    // background-color: green;
    .sms-type {
      height: 100%;

      .head-title {
        display: flex;
        height: 40px;
        line-height: 40px;
        padding: 0 10px;
        border-bottom: 1px solid #e4ede7;
        box-sizing: border-box;

        & > div:nth-child(1) {
          flex: 1;
        }

        & > div:nth-child(2) {
          width: 40px;
          text-align: center;
          background-color: $mainColor;
          color: #fff;
          border-radius: 8px;
          transform: scale(.8);
          cursor: pointer;
          & > i {
            font-size: 18px;
          }
        }
      }

      .sms-type-content {
        height: calc(100% - 40px);
        overflow-y: auto;

        .sms-type-item {
          display: flex;
          height: 40px;
          line-height: 40px;
          padding: 0 10px;
          border-bottom: 1px solid #e4ede7;


          &>div:nth-child(1) {
            flex: 1;
          }

          &>div:nth-child(2) {
            & > span {
              display: inline-block;
              width: 40px;
              text-align: center;
              cursor: pointer;
            }
          }
        }
        
        .sms-type-item:hover {
          border: 1px solid $mainColor;
          color: $mainColor;
        }
      }
    }
  }

  .right-template {
    flex: 3;

    .right-template-head {
      height: 40px;
      line-height: 40px;
      display: flex;
      align-items: center;
      justify-content: end;
      text-align: right;

      .add-btn {
        width: 100px;
        height: 35px;
        line-height: 35px;
        background-color: $mainColor;
        color: #fff;
        text-align: center;
        border-radius: 4px;
        cursor: pointer;
      }
    }

    .right-template-table {
      height: calc(100% - 40px);
    }
  }
}

.sms-phone {
  height: 600px;
  color: $primaryText;

  .content {
    display: flex;
    .sms-content {
      flex: 1;
      // background-color: red;

      .leftToRight-layout {
        width: 100%;

        .label {
          width: 100px;
        }

        .tips {
          width: 100%;
          display: inline-block;
          text-align: right;
        }

        .font-color-red {
          color: #F56C6C;
        }

        .font-size-green {
          color: #67C23A;
        }
      }
    }

    .phone-content {
      width: 300px;
      .phone-img {
        width: 300px;
      }

      .view-content {
        position: relative;
        height: 465px;
        width: 240px;
        top: -518px;
        left: 29px;
        background-color: #f4f4f5;
        border-radius: 12px;
        

        & > div {
          height: 100%;
          overflow-y: auto;
          padding: 8px;
          box-sizing: border-box;
          color: #606266;
        }
      }
    }
  }
}
</style>